#include "StdAfx.h"
#include "DBHelper.h"

HRESULT CDBHelper::Connect()
{
	HRESULT hRet;
	if (m_spConn == NULL)
	{
		try
		{
			_bstr_t conn = GetConnectionString(m_ProductName);
			m_spConn.CreateInstance(__uuidof(ADODB::Connection));
			m_spConn->ConnectionString = conn;
			if (m_spConn->State != ADODB::adStateOpen)
			{
				hRet = m_spConn->Open("", "", "", ADODB::adConnectUnspecified);
			}
		}
		catch(_com_error& e)
		{
			hRet = E_FAIL;
			SetLastErrorString(L"Connect to database fail: %s", e.Description());
		}
	}
	return hRet;
}

HRESULT CDBHelper::Close()
{
	if (IsConnected())
	{
		return m_spConn->Close();
	}
	return S_OK;
}

HRESULT CDBHelper::ExecuteText(BSTR sql, ADODB::_RecordsetPtr &spRecSet)
{
	if (!IsConnected())
	{
		SetLastErrorString(L"Connect to database first!");
		return E_FAIL;
	}
	spRecSet.CreateInstance(__uuidof(ADODB::Recordset));
	VARIANT var;
	var.vt = VT_DISPATCH;
	var.pdispVal = m_spConn;
	spRecSet->CursorLocation = ADODB::adUseClient;
	return spRecSet->Open(sql, var, ADODB::adOpenKeyset, ADODB::adLockOptimistic, ADODB::adCmdText);
}

BOOL CDBHelper::IsConnected()
{
	if (m_spConn!= NULL && m_spConn->State == ADODB::adStateOpen)
	{
		return TRUE;
	}
	return FALSE;
}

HRESULT CDBHelper::GetCommand(ADODB::_CommandPtr& spCmd)
{
	HRESULT hRet = spCmd.CreateInstance(__uuidof(ADODB::Command));
	if (hRet != S_OK)
	{
		return hRet;
	}
	spCmd->ActiveConnection = m_spConn;
	return hRet;
}

HRESULT CDBHelper::GetDataItem(TsDatastoreItemTypeEnum datastoreItemType, INT id, ADODB::_RecordsetPtr& spRS)
{
    INT recordType;
    ADODB::_CommandPtr spCmd;
    GetCommand(spCmd);
    if (datastoreItemType == tsDatastoreItemTypeTestcase)
    {
        recordType = 1;
    }
    else if (datastoreItemType == tsDatastoreItemTypeResult)
    {
        recordType = 2;
    }
    else
    {
        SetLastErrorString(L"Incorrect datastoreItemtype!");
        return FALSE;
    }
    spCmd->CommandType = ADODB::adCmdStoredProc;
    spCmd->CommandText = L"GetDataItem";
    ADODB::_ParameterPtr spParamRecordType = spCmd->CreateParameter(L"@RecordType", ADODB::adInteger, ADODB::adParamInput, sizeof(INT));
    ADODB::_ParameterPtr spParamId = spCmd->CreateParameter(L"@Id", ADODB::adInteger, ADODB::adParamInput, sizeof(INT));
    spParamRecordType->Value = recordType;
    spParamId->Value = id;
    spCmd->Parameters->Append(spParamRecordType);
    spCmd->Parameters->Append(spParamId);

    spRS = spCmd->Execute(NULL, NULL, NULL);
    return TRUE;
}


_bstr_t CDBHelper::GetConnectionString(_bstr_t prodctName)
{
	CComSafeArray<BSTR> safeArray;
	GetConnectingStrings(safeArray);
	LONG alIndex[] = {0, 0};
	ULONG count = safeArray.GetCount(1);
	for(ULONG i=0; i<count; i++)
	{
		BSTR name;
		BSTR strConn;
		alIndex[0] = 0;
		safeArray.MultiDimGetAt(alIndex, name);
		alIndex[0] = 1;
		safeArray.MultiDimGetAt(alIndex, strConn);
		if (_bstr_t(name) == prodctName)
		{
			return strConn;
		}
		alIndex[1]++;
	}
	return _bstr_t();
}

HRESULT CDBHelper::GetConnectingStrings(CComSafeArray<BSTR>& safeArray)
{
	
	HRESULT hr;
	ADODB::_CommandPtr spCmd;
	
	_bstr_t tsConn;

	hr = CConfigMgr::GetInstance().GetConnectionString(L"TestStudio", tsConn);
	if (FAILED(hr))
	{
		return hr;
	}
	//BSTR conn = GetTSConnectionString();

	ADODB::_ConnectionPtr spConn;
	spConn.CreateInstance(__uuidof(ADODB::Connection));
	spConn->ConnectionString = tsConn;
	spConn->Open("", "", "", ADODB::adConnectUnspecified);
	hr = spCmd.CreateInstance(__uuidof(ADODB::Command));
	if (hr != S_OK)
	{
		return hr;
	}
	spCmd->ActiveConnection = spConn;

	spCmd->CommandType = ADODB::adCmdStoredProc;
	spCmd->CommandText = L"usp_GetDSCatalog";
	_variant_t productCount;
	ADODB::_RecordsetPtr spRS = spCmd->Execute(&productCount, NULL, NULL);
	
	CComSafeArrayBound bound(productCount.intVal);
	safeArray.Create(&bound, 2);
	//(
	LONG alIndex[] = {0, 0};
	while(!spRS->adoEOF)
	{
		_bstr_t name = spRS->Fields->Item[L"Name"]->Value.bstrVal;
		_bstr_t strConn = spRS->Fields->Item[L"ConnectionString"]->Value.bstrVal;
		alIndex[0] = 0;
		safeArray.MultiDimSetAt(alIndex, name);
		alIndex[0] = 1;
		safeArray.MultiDimSetAt(alIndex, strConn);
		alIndex[1]++;
		spRS->MoveNext();
	}
	return TRUE;
}



//HRESULT CDBHelper::GetDatastoreItem(TsDatastoreItemTypeEnum itemType, int id, IDatastoreItem** ppDatastoreItem)
//{
//	ADODB::_RecordsetPtr spRS;
//    if (!GetDataItem(itemType, id, spRS))
//    {
//        BSTR err = GetLastErrorString();
//        //Error(err);
//        return E_FAIL;
//    }
//	CComObject<CDatastoreItem> * pDsItem = GetComObject<CDatastoreItem>();
//	pDsItem->m_DBHelper = this;
//	pDsItem->m_Id = id;
//	pDsItem->m_Type = itemType;
//	
//	*ppDatastoreItem = pDsItem;
//	return S_OK;
//}
